<template>
      <div class="app-container">
        <el-form ref="form" :model="form" :rules="formRules" label-width="120px" size="medium">
            <el-form-item label="机台编号" prop="machineId" >
                <el-input v-model="form.machineId" style="width:300px" />
            </el-form-item>
            <el-form-item label="机台名称" prop="machineName">
                <el-input v-model="form.machineName" style="width:300px" />
            </el-form-item>
            <el-form-item label="机台类型" prop="machineType">
                <el-select v-model="form.machineType" @change="machineTypechange" placeholder="请选择机台类型" style="width:300px">
                    <el-option :value="item" :label="item" v-for="(item,index) in this.belongList" :key="index"/>
                </el-select>
            </el-form-item>
            <el-form-item label="部门" prop="department">
                <el-select v-model="form.department" placeholder="请选择部门" @focus="getCenterList" @change="getCenterchange" style="width:300px">
                  <el-option :value="item" :label="item" v-for="(item,index) in this.centerList" :key="index"/>
                </el-select>
                <!-- <el-input v-model="form.department" style="width:300px" /> -->
            </el-form-item>
            <!-- <el-form-item label="员工岗位职级" prop="jobClass">
                <el-cascader collapse-tags :props="props" v-model="form.jobClass" separator="-" :options="options" clearable style="width:300px"/>
            </el-form-item> -->
            <el-form-item label="岗位职级" prop="jobClass">
                <div v-for="(items,index1) in trainObjList" :key="index1" style="margin-bottom: 5px;">
                  <el-cascader v-model="items.jobTitle" :options="trainList" @focus="getKnowledge(form.department)" clearable @change="objChang($event,index1)" class="ul-item"  style="width: 300px;"/>
                <!-- <el-button style="margin-left: 5px;" type="danger" icon="el-icon-delete" circle @click="delPost(index1)"></el-button>
                <el-button v-if="index1 == 0" style="margin-left: 5px;" type="primary" icon="el-icon-plus" circle @click="addPost"></el-button> -->
              </div>
            </el-form-item>
            <el-form-item label="工段编号" prop="sectionNo">
                <el-input v-model="form.sectionNo" @blur="checkSectionExist" style="width:300px" />
            </el-form-item>
            <el-form-item label="最大人数限制" prop="qualityMax" v-if="form.isMore == 1">
                <el-input-number size="mini" v-model="form.qualityMax" :min="1" :max="5" ></el-input-number>
            </el-form-item>
            <el-form-item label="是否多人绑定" prop="isMore" v-if="!['喷涂一线', '喷涂二线', '喷涂三线', '喷涂样品线'].includes(form.machineType)">
                <el-switch v-model="form.isMore" active-value="1" inactive-value="0" active-text="是" inactive-text="否" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('form')">添加</el-button>
                <el-button type="primary" @click="resetForm('form')">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { saveMachine } from '../../api/machine'
import { WorkSecExist,getCenter } from '../../api/workSection.js'
import { knowledgeFind } from "@/api/knowledgeSkill"
export default {
    name: 'add_machine',
    data() {
        return {
            form: {
                machineId: '',          //机台号
                machineName: '',        //机台名称
                department: '',         //部门
                jobClass: '',           //职级
                sectionNo: '',          //工段编号
                machineType: '',        //机台类型
                isMore: 0,                //是否多人绑定
                qualityMax: '1'
            },
            belongList:['装配','数冲','折弯','钳铆','人工焊组','机器人组','打磨组','喷涂一线','喷涂二线','喷涂三线','喷涂样品线','走芯机','CNC','其他'],
            // 岗位职级下拉选项信息
            options: [{
                value: 'O1',
                label: 'O1',
                children: [{
                value: '1',
                label: '1'
                }, {
                value: '2',
                label: '2'
                }, {
                value: '3',
                label: '3'
                }, {
                value: '4',
                label: '4'
                }, {
                value: '5',
                label: '5'
                }]
            }, {
                value: 'O2',
                label: 'O2',
                children: [{
                value: '1',
                label: '1'
                }, {
                value: '2',
                label: '2'
                }, {
                value: '3',
                label: '3'
                }, {
                value: '4',
                label: '4'
                }, {
                value: '5',
                label: '5'
                }]
            }, {
                value: 'O3',
                label: 'O3',
                children: [{
                value: '1',
                label: '1'
                }, {
                value: '2',
                label: '2'
                }, {
                value: '3',
                label: '3'
                }, {
                value: '4',
                label: '4'
                }, {
                value: '5',
                label: '5'
                }]
            },  {
                value: 'O4',
                label: 'O4',
                children: [{
                value: '1',
                label: '1'
                }, {
                value: '2',
                label: '2'
                }, {
                value: '3',
                label: '3'
                }, {
                value: '4',
                label: '4'
                }, {
                value: '5',
                label: '5'
                }]
            }, {
                value: 'O5',
                label: 'O5',
                children: [{
                value: '1',
                label: '1'
                }, {
                value: '2',
                label: '2'
                }, {
                value: '3',
                label: '3'
                }, {
                value: '4',
                label: '4'
                }, {
                value: '5',
                label: '5'
                }]
            }],
            formRules: {
                machineId: [
                    { required: true, message: '请输入机台号', trigger: 'blur' }
                ],
                machineName: [
                    { required: true, message: '请输入机台名称', trigger: 'blur' }
                ],
                machineType: [
                    { required: true, message: '请选择机台类型', trigger: 'blur' }
                ],
                department: [
                    { required: true, message: '请输入部门', trigger: 'blur' }
                ],
                // jobClass: [
                //     { required: true, message: '请选择职级', trigger: 'blur' }
                // ],
                sectionNo: [
                    { required: true, message: '请输入工段编号', trigger: 'blur' }
                ],
                qualityMax: [
                    { required: true, message: '最大人数限制不能为空', trigger: 'blur' }
                ],
            },
            props: { multiple: true },
            centerList: [],
            trainObjList:[{jobTitle:''}],
            trainList:[],
        }
    },
    methods: {
        getCenterchange(){
            this.trainObjList = [{jobTitle:''}],
            this.trainList = []
        },
        // 机台类型改变
        machineTypechange(e){
            this.form.isMore = 0
            if(['喷涂一线', '喷涂二线', '喷涂三线', '喷涂样品线'].includes(e)){
                this.form.isMore = 1
            }
        },
        // 对表单进行重置
        resetForm(formItem) {
            this.$refs[formItem].resetFields()
        },
        // 提交表单之前先进行验证
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.submit()
                } else {
                    return false
                }
            })
        },
        // 岗位对象发生改变
        objChang(e,index1){
          console.log(e,index1)
          const id = e[2]
          this.trainObjList[index1].id = id
            // this.trainObjList[index1].jobTitle = item.jobTitle
      },
        // 添加岗位职级
        addPost(){
        this.trainObjList.push({jobTitle:''})
      },
      // 删除岗位职级
      delPost(index){
        if(this.trainObjList.length == 1){
          this.trainObjList = [{jobTitle:''}]
        } else {
          this.trainObjList.splice(index, 1);
        }
      },
      async getKnowledge(workCenter){
        console.log('workCenter',workCenter)
          let query = {page:1,limit:9999}
          if(!workCenter)return this.$message.warning('请先选择部门！')
          if(workCenter){query.workCenter = workCenter}
          const {data} = await knowledgeFind(query)
          if(!data.list.length) return this.$message.warning(`${workCenter}没有查到岗位信息！`)
          this.traList = data.list
          const map = data.list.map(item => item.workCenter)
          const seenIds = new Set();
          // 拿到级别去重的数组
          const rankOfPositionArr = data.list.filter(item => {
              if (!seenIds.has(item.rankOfPosition)) {
                  seenIds.add(item.rankOfPosition);
                  return true;
              }
              return false;
          });
          const uniqueArray = [...new Set(map)]; 
          this.trainList = uniqueArray.map(item =>({
          value: item,
          label: item,
          // value: item,
          // label: item == 1 ? '试用级':item == 2 ? '初级':item == 3 ? '中级':item == 4 ? '高级':item == 5 ? '师傅级':'',
          children: rankOfPositionArr.map(e => ({
            value: e.rankOfPosition,
            label: e.rankOfPosition == 1 ? '试用级':e.rankOfPosition == 2 ? '初级':e.rankOfPosition == 3 ? '中级':e.rankOfPosition == 4 ? '高级':e.rankOfPosition == 5 ? '师傅级':'',
            children: data.list.filter(v => v.rankOfPosition == e.rankOfPosition && item == v.workCenter).map(v1 => ({
              value: v1.id,
              label: v1.jobTitle,
              }))
            }))
          }))
        console.log(this.trainList)
    },
        // 提交机台表单信息
        async submit() {
          let query = Object.assign({},this.form)
          let arr1 = []
          console.log(this.trainObjList)
          if(!this.trainObjList.length) return this.$message.warning('请选择岗位职级！')
          this.trainObjList.forEach(item => {
              arr1.push(item.id)
          })
          query.jobClass = arr1.join(',')
        //   if(this.form.jobClass.length) {
        //     let array = []
        //     // this.form.jobClass.forEach(item => {
        //     //     array.push(item.join('-'))
        //     // });
        //     array = this.form.jobClass.join('-')
        //     query.jobClass = array
        //   }
          if(query.isMore == 0) {
            delete query.qualityMax
          }
          // if(this.form.machineType == '喷涂一线' || this.form.machineType == '喷涂二线' || this.form.machineType == '喷涂三线' || this.form.machineType == '喷涂样品线') {
          //   delete query.isMore
          //   query.isSpray = true
          // } else {  delete query.qualityMax }
          const data = await saveMachine(query)
          const errMsg = data.msg
          if(data.code == '1') {
            this.$message({
              showClose: true,
              message: errMsg,
              type: 'success'
            })
          } else {
            this.$message({
              showClose: true,
              message: errMsg,
              type: 'warning'
            })
          }
        },
        // 当焦点移开input输入框触发该函数，检查工段编号是否已经注册
        async checkSectionExist() {
        const data = await WorkSecExist({sectionNo: this.form.sectionNo})
        let errormsg = data.msg
        if(data.code =='79'){
              this.$message({
                type: 'success ',
                message: '工段编号验证通过'
            })
        } else if(data.code =='1'){
            this.$message({
                type: 'warning',
                message: '工段编号不存在！'
            })
        } else {
            this.$message({
                type: 'warning',
                message: errormsg
            })
        }
        },
        // 获取工作中心
        async getCenterList() {
          let {data} = await getCenter()
          this.centerList = data
        },
    },
    // 进入页面获取table信息
    mounted() {
    }
}
</script>

<style>

</style>
